package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.BasePermissionDao;
import com.hhs.storage.service.BasePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.BasePermissionUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-01-09
 */
@Service
@Transactional
public class BasePermissionServiceImpl extends ServiceImpl<BasePermissionDao, BasePermission> implements BasePermissionService {


    @Resource
    BasePermissionUserService basePermissionUserService;

    @Override
    public Map<String, Object> getAll(InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<BasePermission>();
        ew.orderByDesc("sort_id");
        List<BasePermission> list = this.list(ew);
        return ResponseInfo.success(list);
    }

    @Override
    public List<BasePermission> getByUserId(String userId) {
        if(StringUtils.isEmpty(userId)){
            return new ArrayList<>();
        }

        List<BasePermission> list = this.baseMapper.getByUserId(userId);
        return list;
    }

    @Override
    public Boolean hasPermission(String userId, String permissionFlag) {
        //系统管理所有权限都有
        if ("2".equals(userId)) {
            return true;
        }
        List<BasePermission> permissions = this.getByUserId(userId);
        for (BasePermission perm :
                permissions) {
            if (permissionFlag.equals(perm.getFlag())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> configData(boolean status, String perId, String userId) {
        BasePermissionUser addData = new BasePermissionUser();
        addData.setPerId(perId);
        addData.setUserId(userId);
        QueryWrapper ew = new QueryWrapper<BasePermissionUser>();
        ew.eq("per_id",perId);
        ew.eq("user_id",userId);
        BasePermissionUser data = basePermissionUserService.getOne(ew);
        if(status){
            //true 就添加，判断存不存在，存在则不动
            if(data==null){
                basePermissionUserService.save(addData);
            }
        }else{
            //false 就删除
            if(data !=null) {
                basePermissionUserService.removeById(data.getId());
            }
        }

        return null;
    }

}
